import { ref } from 'vue'

// 事件总线的替代方案
class EventBus {
  constructor() {
    this.events = {}
  }

  // 监听事件
  on(event, callback) {
    if (!this.events[event]) {
      this.events[event] = []
    }
    this.events[event].push(callback)
  }

  // 移除事件监听
  off(event, callback) {
    if (!this.events[event]) return
    
    if (callback) {
      const index = this.events[event].indexOf(callback)
      if (index > -1) {
        this.events[event].splice(index, 1)
      }
    } else {
      this.events[event] = []
    }
  }

  // 触发事件
  emit(event, ...args) {
    if (!this.events[event]) return
    
    this.events[event].forEach(callback => {
      callback(...args)
    })
  }

  // 只监听一次
  once(event, callback) {
    const onceCallback = (...args) => {
      callback(...args)
      this.off(event, onceCallback)
    }
    this.on(event, onceCallback)
  }
}

// 创建全局事件总线实例
const eventBus = new EventBus()

// 导出使用事件总线的组合式函数
export function useEventBus() {
  return {
    $on: eventBus.on.bind(eventBus),
    $off: eventBus.off.bind(eventBus),
    $emit: eventBus.emit.bind(eventBus),
    $once: eventBus.once.bind(eventBus)
  }
}

// 直接导出事件总线实例
export default eventBus